/**
 * v-auth
 * 按钮权限指令
 */
import { useAuthStore } from "@/stores/modules/auth";
import type { Directive, DirectiveBinding } from "vue";

const auth: Directive = {
  mounted(el: HTMLElement, binding: DirectiveBinding) {
    const { value, arg } = binding;
    const authStore = useAuthStore();
    const currentPageRoles = arg
      ? authStore.authButtonListGet[arg] ?? []
      : authStore.authButtonListGet[authStore.routeName] ?? [];
    if (value instanceof Array && value.length) {
      const hasPermission = value.every(item => currentPageRoles.includes(item));
      if (!hasPermission) el.remove();
    } else if (typeof value === "object") {
      if (value.hasOwnProperty("has")) {
        const hasPermission = value.has.every(item => currentPageRoles.includes(item));
        if (!hasPermission) el.remove();
      } else if (value.hasOwnProperty("not")) {
        const hasPermission = value.not.every(item => !currentPageRoles.includes(item));
        if (hasPermission) el.remove();
      } else {
        throw new Error("v-auth: has or not is required");
      }
    } else {
      if (!currentPageRoles.includes(value)) el.remove();
    }
  }
};

export default auth;
